<template>
  <div class="p-2">
    <transition :enter-active-class="proxy?.animate.searchAnimate.enter" :leave-active-class="proxy?.animate.searchAnimate.leave">
      <div v-show="showSearch" class="mb-[10px]">
        <el-card shadow="hover">
          <el-form ref="queryFormRef" :model="queryParams" :inline="true">
            <el-form-item label="农户名称" prop="farmerName">
              <el-input v-model="queryParams.farmerName" placeholder="请输入农户名称" clearable @keyup.enter="handleQuery" />
            </el-form-item>
            <el-form-item label="身份证号" prop="farmerIdCard">
              <el-input v-model="queryParams.farmerIdCard" placeholder="请输入身份证号" clearable @keyup.enter="handleQuery" />
            </el-form-item>
            <el-form-item label="地块总数" prop="plotCount">
              <el-input v-model="queryParams.plotCount" placeholder="请输入地块总数" clearable @keyup.enter="handleQuery" />
            </el-form-item>
            <el-form-item label="实测面积" prop="measuredArea">
              <el-input v-model="queryParams.measuredArea" placeholder="请输入实测面积" clearable @keyup.enter="handleQuery" />
            </el-form-item>
            <el-form-item label="投保面积" prop="insuredArea">
              <el-input v-model="queryParams.insuredArea" placeholder="请输入投保面积" clearable @keyup.enter="handleQuery" />
            </el-form-item>
            <el-form-item label="家庭成员姓名" prop="familyMemberName">
              <el-input v-model="queryParams.familyMemberName" placeholder="请输入家庭成员姓名" clearable @keyup.enter="handleQuery" />
            </el-form-item>
            <el-form-item label="家庭成员身份证号" prop="familyMemberIdCard">
              <el-input v-model="queryParams.familyMemberIdCard" placeholder="请输入家庭成员身份证号" clearable @keyup.enter="handleQuery" />
            </el-form-item>
            <el-form-item>
              <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
              <el-button icon="Refresh" @click="resetQuery">重置</el-button>
            </el-form-item>
          </el-form>
        </el-card>
      </div>
    </transition>

    <el-card shadow="never">
      <template #header>
        <el-row :gutter="10" class="mb8">
          <el-col :span="1.5">
            <el-button type="primary" plain icon="Plus" @click="handleAdd" v-hasPermi="['Nyt7FarmerInsuranceInfo:Nyt7FarmerInsuranceInfo:add']">新增</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="success" plain icon="Edit" :disabled="single" @click="handleUpdate()" v-hasPermi="['Nyt7FarmerInsuranceInfo:Nyt7FarmerInsuranceInfo:edit']">修改</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="danger" plain icon="Delete" :disabled="multiple" @click="handleDelete()" v-hasPermi="['Nyt7FarmerInsuranceInfo:Nyt7FarmerInsuranceInfo:remove']">删除</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="warning" plain icon="Download" @click="handleExport" v-hasPermi="['Nyt7FarmerInsuranceInfo:Nyt7FarmerInsuranceInfo:export']">导出</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="warning" plain icon="Upload" @click="handleImport" v-hasPermi="['Nyt7FarmerInsuranceInfo:Nyt7FarmerInsuranceInfo:export']"
            >导入</el-button
            >
          </el-col>
          <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
        </el-row>
      </template>

      <el-table v-loading="loading" :data="Nyt7FarmerInsuranceInfoList" @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column label="序号" align="center" width="60">
          <template #default="scope">
            {{ (queryParams.pageNum - 1) * queryParams.pageSize + scope.$index + 1 }}
          </template>
        </el-table-column>
        <el-table-column label="农户名称" align="center" prop="farmerName" />
        <el-table-column label="身份证号" align="center" prop="farmerIdCard" />
        <el-table-column label="地块总数" align="center" prop="plotCount" />
        <el-table-column label="实测面积" align="center" prop="measuredArea" />
        <el-table-column label="投保面积" align="center" prop="insuredArea" />
        <el-table-column label="家庭成员姓名" align="center" prop="familyMemberName" />
        <el-table-column label="家庭成员身份证号" align="center" prop="familyMemberIdCard" />
        <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
          <template #default="scope">
            <!-- 详情 -->
            <el-tooltip content="详情" placement="top">
              <el-button link type="primary" icon="View" @click="handleView(scope.row)" v-hasPermi="['Nyt7FarmerInsuranceInfo:Nyt7FarmerInsuranceInfo:edit']"></el-button>
            </el-tooltip>
            <el-tooltip content="修改" placement="top">
              <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)" v-hasPermi="['Nyt7FarmerInsuranceInfo:Nyt7FarmerInsuranceInfo:edit']"></el-button>
            </el-tooltip>
            <el-tooltip content="删除" placement="top">
              <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)" v-hasPermi="['Nyt7FarmerInsuranceInfo:Nyt7FarmerInsuranceInfo:remove']"></el-button>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>

      <pagination v-show="total > 0" :total="total" v-model:page="queryParams.pageNum" v-model:limit="queryParams.pageSize" @pagination="getList" />
    </el-card>

    <!--数据导入对话框 -->
    <el-dialog title="数据导入" v-model="excelOpen" width="400px" append-to-body>
      <el-upload
        ref="uploadRef"
        class="upload-demo"
        :auto-upload="false"
        :on-change="handleChange"
        :limit="1"
        accept=".xlsx,.xls">
        <template #trigger>
          <el-button type="primary">选择文件</el-button>
        </template>
        <el-button class="ml-3" type="success" @click="submitUpload">上传</el-button>
        <template #tip>
          <el-button class="ml-3" type="success" @click="handleExportTemplate">下载导入模版</el-button>
          <div class="el-upload__tip">上传文件仅支持，xls/xlsx格式，文件大小不得超过20M</div>
        </template>
      </el-upload>
    </el-dialog>

    <!-- 添加或修改农户投保信息对话框 -->
    <el-dialog :title="dialogEdit.title" v-model="dialogEdit.visible" width="800px" append-to-body>
      <el-form ref="Nyt7FarmerInsuranceInfoFormRef" :model="form" :rules="rules" label-width="110px">
        <el-card class="mb-4">
          <el-row :gutter="20">
            <el-col :span="12">
        <el-form-item label="农户名称" prop="farmerName">
          <el-input v-model="form.farmerName" placeholder="请输入农户名称" />
        </el-form-item></el-col><el-col :span="12">
        <el-form-item label="身份证号" prop="farmerIdCard">
          <el-input v-model="form.farmerIdCard" placeholder="请输入身份证号" />
        </el-form-item></el-col><el-col :span="12">
        <el-form-item label="地块总数" prop="plotCount">
          <el-input v-model="form.plotCount" placeholder="请输入地块总数" />
        </el-form-item></el-col><el-col :span="12">
        <el-form-item label="实测面积" prop="measuredArea">
          <el-input v-model="form.measuredArea" placeholder="请输入实测面积" />
        </el-form-item></el-col><el-col :span="12">
        <el-form-item label="投保面积" prop="insuredArea">
          <el-input v-model="form.insuredArea" placeholder="请输入投保面积" />
        </el-form-item></el-col><el-col :span="12">
        <el-form-item label="家庭成员姓名" prop="familyMemberName">
          <el-input v-model="form.familyMemberName" placeholder="请输入家庭成员姓名" />
        </el-form-item></el-col><el-col :span="12">
        <el-form-item label="家庭成员身份证号" label-width="160px" prop="familyMemberIdCard">
          <el-input v-model="form.familyMemberIdCard" placeholder="请输入家庭成员身份证号" />
        </el-form-item></el-col></el-row>
        </el-card>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button :loading="buttonLoading" type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>



    <!-- 详情对话框 -->
<el-dialog :title="dialogView.title" v-model="dialogView.visible" width="800px" append-to-body>
  <el-form ref="Nyt7FarmerInsuranceInfoFormRef" :model="form2"  label-width="110px" disabled>
    <el-card class="mb-4">
      <template #header>
        <div class="card-header">
          <span class="title">农户基本信息</span>
        </div>
      </template>
      <el-descriptions :column="2" border>

          <el-descriptions-item label="农户名称" prop="farmerName">
            {{ form2.farmerName }}
          </el-descriptions-item>

          <el-descriptions-item label="身份证号" prop="farmerIdCard">
            {{ form2.farmerIdCard }}
          </el-descriptions-item>

          <el-descriptions-item label="地块总数" prop="plotCount">
            {{ form2.plotCount }}
          </el-descriptions-item>

          <el-descriptions-item label="实测面积" prop="measuredArea">
            {{ form2.measuredArea }}
          </el-descriptions-item>

          <el-descriptions-item label="投保面积" prop="insuredArea">
            {{ form2.insuredArea }}
          </el-descriptions-item>

          <el-descriptions-item label="家庭成员姓名" prop="familyMemberName">
            {{ form2.familyMemberName }}
          </el-descriptions-item>

          <el-descriptions-item label="家庭成员身份证号" label-width="160px" prop="familyMemberIdCard">
            {{ form2.familyMemberIdCard }}
          </el-descriptions-item>
      </el-descriptions>
    </el-card>
    <el-card class="mb-4">
      <template #header>
        <div class="card-header">
          <span class="title">其它信息</span>
        </div>
      </template>
      <el-descriptions :column="2" border>

        <el-descriptions-item label="认证状态" label-width="160px" prop="certificationStatus">
          {{ form2.certificationStatus }}
        </el-descriptions-item>
        <el-descriptions-item label="注册时间" label-width="160px" prop="registrationTime">
          {{ form2.registrationTime }}
        </el-descriptions-item>
        <el-descriptions-item label="手机号" label-width="160px" prop="phone">
          {{ form2.phone }}
        </el-descriptions-item>
        <el-descriptions-item label="省" label-width="160px" prop="province">
          {{ form2.province }}
        </el-descriptions-item>
        <el-descriptions-item label="市" label-width="160px" prop="city">
          {{ form2.city }}
        </el-descriptions-item>
        <el-descriptions-item label="区/县" label-width="160px" prop="district">
          {{ form2.district }}
        </el-descriptions-item>
        <el-descriptions-item label="主体等级" label-width="160px" prop="principalLevel">
          {{ form2.principalLevel }}
        </el-descriptions-item>
        <el-descriptions-item label="经营主体名称" label-width="160px" prop="businessName">
          {{ form2.businessName }}
        </el-descriptions-item>
        <el-descriptions-item label="经营业务" label-width="160px" prop="businessOperations">
          {{ form2.businessOperations }}
        </el-descriptions-item>
        <el-descriptions-item label="注册地址" label-width="160px" prop="registeredAddress">
          {{ form2.registeredAddress }}
        </el-descriptions-item>
        <el-descriptions-item label="工商执照号" label-width="160px" prop="businessLicense">
          {{ form2.businessLicense }}
        </el-descriptions-item>
      </el-descriptions>
    </el-card>
  </el-form>
  <template #footer>
    <div class="dialog-footer">
      <el-button @click="cancel">返 回</el-button>
    </div>
  </template>
</el-dialog>

  </div>
</template>

<script setup name="Nyt7FarmerInsuranceInfo" lang="ts">
import { listNyt7FarmerInsuranceInfo, getNyt7FarmerInsuranceInfo, delNyt7FarmerInsuranceInfo, addNyt7FarmerInsuranceInfo, updateNyt7FarmerInsuranceInfo ,exportSelected} from '@/api/Nyt7FarmerInsuranceInfo/Nyt7FarmerInsuranceInfo';
import {
  Nyt7FarmerInsuranceInfoVO,
  Nyt7FarmerInsuranceInfoQuery,
  Nyt7FarmerInsuranceInfoForm,
  Nyt7FarmerInsuranceInfo
} from '@/api/Nyt7FarmerInsuranceInfo/Nyt7FarmerInsuranceInfo/types';
import { importExcel } from '@/api/Nyt7FarmerInsuranceInfo/Nyt7FarmerInsuranceInfo';


const { proxy } = getCurrentInstance() as ComponentInternalInstance;

const Nyt7FarmerInsuranceInfoList = ref<Nyt7FarmerInsuranceInfoVO[]>([]);
const buttonLoading = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref<Array<string | number>>([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);

const queryFormRef = ref<ElFormInstance>();
const Nyt7FarmerInsuranceInfoFormRef = ref<ElFormInstance>();

const selectedRows = ref<Nyt7FarmerInsuranceInfoVO[]>([]);
// 多选框选中数据
const handleSelectionChange = (selection: Nyt7FarmerInsuranceInfoVO[]) => {
  ids.value = selection.map(item => item.id);
  selectedRows.value = selection; // 存储选中的数据行
  single.value = selection.length != 1;
  multiple.value = !selection.length;
}

const dialogEdit = reactive<DialogOption>({
  visible: false,
  title: ''
});

const dialogView = reactive<DialogOption>({
  visible: false,
  title: ''
});


const initFormData2: Nyt7FarmerInsuranceInfo = {
  id: undefined,
  farmerName: undefined,
  farmerIdCard: undefined,
  plotCount: undefined,
  measuredArea: undefined,
  insuredArea: undefined,
  familyMemberName: undefined,
  familyMemberIdCard: undefined,

  /**
   * 认证状态
   */
  certificationStatus:undefined,

  /**
   * 注册时间
   */
  registrationTime:undefined,

  /**
   * 手机号
   */
  phone:undefined,

  /**
   * 省
   */
  province:undefined,

  /**
   * 市
   */
  city:undefined,

  /**
   * 区/县
   */
  district:undefined,

  /**
   * 主体等级
   */
  principalLevel:undefined,
  /**
   * 经营主体名称
   */
  businessName:undefined,

  /**
   * 经营业务
   */
  businessOperations:undefined,

  /**
   * 注册地址
   */
  registeredAddress:undefined,

  /**
   * 工商执照号
   */
  businessLicense:undefined,
}
const data2 = reactive<PageData<Nyt7FarmerInsuranceInfo, Nyt7FarmerInsuranceInfoQuery>>({
  form: { ...initFormData2 },
})

const initFormData: Nyt7FarmerInsuranceInfoForm = {
  id: undefined,
  farmerName: undefined,
  farmerIdCard: undefined,
  plotCount: undefined,
  measuredArea: undefined,
  insuredArea: undefined,
  familyMemberName: undefined,
  familyMemberIdCard: undefined,
}
const data = reactive<PageData<Nyt7FarmerInsuranceInfoForm, Nyt7FarmerInsuranceInfoQuery>>({
  form: {...initFormData},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    farmerName: undefined,
    farmerIdCard: undefined,
    plotCount: undefined,
    measuredArea: undefined,
    insuredArea: undefined,
    familyMemberName: undefined,
    familyMemberIdCard: undefined,
    params: {
    }
  },
  rules: {
    id: [
      { required: true, message: "id不能为空", trigger: "blur" }
    ],
    farmerName: [
      { required: true, message: "农户名称不能为空", trigger: "blur" }
    ],
    farmerIdCard: [
      { required: true, message: "身份证号不能为空", trigger: "blur" }
    ],
    plotCount: [
      { required: true, message: "地块总数不能为空", trigger: "blur" }
    ],
    measuredArea: [
      { required: true, message: "实测面积不能为空", trigger: "blur" }
    ],
    insuredArea: [
      { required: true, message: "投保面积不能为空", trigger: "blur" }
    ],
    familyMemberName: [
      { required: true, message: "家庭成员姓名不能为空", trigger: "blur" }
    ],
    familyMemberIdCard: [
      { required: true, message: "家庭成员身份证号不能为空", trigger: "blur" }
    ],
  }
});

const { queryParams, form, rules } = toRefs(data);
const { form:form2 } = toRefs(data2);
/** 查询农户投保信息列表 */
const getList = async () => {
  loading.value = true;
  const res = await listNyt7FarmerInsuranceInfo(queryParams.value);
  Nyt7FarmerInsuranceInfoList.value = res.rows;
  total.value = res.total;
  loading.value = false;
}

/** 取消按钮 */
const cancel = () => {
  reset();
  dialogEdit.visible = false;
  dialogView.visible = false;
}

/** 表单重置 */
const reset = () => {
  form.value = {...initFormData};
  Nyt7FarmerInsuranceInfoFormRef.value?.resetFields();
}

/** 搜索按钮操作 */
const handleQuery = () => {
  queryParams.value.pageNum = 1;
  getList();
}

/** 重置按钮操作 */
const resetQuery = () => {
  queryFormRef.value?.resetFields();
  handleQuery();
}

// /** 多选框选中数据 */
// const handleSelectionChange = (selection: Nyt7FarmerInsuranceInfoVO[]) => {
//   ids.value = selection.map(item => item.id);
//   single.value = selection.length != 1;
//   multiple.value = !selection.length;
// }

/** 新增按钮操作 */
const handleAdd = () => {
  reset();
  dialogEdit.visible = true;
  dialogEdit.title = "添加农户投保信息";
}

/** 修改按钮操作 */
const handleUpdate = async (row?: Nyt7FarmerInsuranceInfoVO) => {
  reset();
  const _id = row?.id || ids.value[0]
  const res = await getNyt7FarmerInsuranceInfo(_id);
  Object.assign(form.value, res.data);
  dialogEdit.visible = true;
  dialogEdit.title = "修改农户投保信息";
}

/** 提交按钮 */
const submitForm = () => {
  Nyt7FarmerInsuranceInfoFormRef.value?.validate(async (valid: boolean) => {
    if (valid) {
      buttonLoading.value = true;
      if (form.value.id) {
        await updateNyt7FarmerInsuranceInfo(form.value).finally(() =>  buttonLoading.value = false);
      } else {
        await addNyt7FarmerInsuranceInfo(form.value).finally(() =>  buttonLoading.value = false);
      }
      proxy?.$modal.msgSuccess("操作成功");
      dialogEdit.visible = false;
      await getList();
    }
  });
}

/** 删除按钮操作 */
const handleDelete = async (row?: Nyt7FarmerInsuranceInfoVO) => {
  const _ids = row?.id || ids.value;
  await proxy?.$modal.confirm('是否确认删除农户投保信息编号为"' + _ids + '"的数据项？').finally(() => loading.value = false);
  await delNyt7FarmerInsuranceInfo(_ids);
  proxy?.$modal.msgSuccess("删除成功");
  await getList();
}


// /** 导出按钮操作 */
// const handleExport = () => {
//   proxy?.download('Nyt7FarmerInsuranceInfo/Nyt7FarmerInsuranceInfo/export', {
//     ...queryParams.value
//   }, `Nyt7FarmerInsuranceInfo_${new Date().getTime()}.xlsx`)
// }


const handleExport = () => {
  if (selectedRows.value.length > 0) {
    // 导出选中的数据
    exportSelectedRows(selectedRows.value);
  } else {
    // 导出所有数据
    proxy?.download('Nyt7FarmerInsuranceInfo/Nyt7FarmerInsuranceInfo/export', {
      ...queryParams.value
    }, `Nyt7FarmerInsuranceInfo_${new Date().getTime()}.xlsx`);
  }
}

// // 修改 exportSelectedRows 方法
// const exportSelectedRows = async (rows: Nyt7FarmerInsuranceInfoVO[]) => {
//   try {
//     const response = await exportSelected(rows.map(row => row.id));
//     const url = window.URL.createObjectURL(new Blob([response]));
//     const link = document.createElement('a');
//     link.href = url;
//     link.setAttribute('download', `Nyt7FarmerInsuranceInfo_${new Date().getTime()}.xlsx`);
//     document.body.appendChild(link);
//     link.click();
//   } catch (error) {
//     console.error('导出选中的数据失败:', error);
//     proxy?.$modal.msgError('导出选中的数据失败');
//   }
// }

const exportSelectedRows = async (rows: Nyt7FarmerInsuranceInfoVO[]) => {
  try {
    console.log('开始导出选中的数据:', rows);
    const ids = rows.map(row => row.id);
    console.log('选中的数据ID列表:', ids);
    const response = await exportSelected(ids);
    console.log('导出响应:', response);
    const url = window.URL.createObjectURL(new Blob([response]));
    console.log('创建的URL:', url);
    const link = document.createElement('a');
    link.href = url;
    link.setAttribute('download', `Nyt7FarmerInsuranceInfo_${new Date().getTime()}.xlsx`);
    console.log('创建的下载链接:', link);
    document.body.appendChild(link);
    link.click();
    console.log('下载链接点击完成');
  } catch (error) {
    console.error('导出选中的数据失败:', error);
    proxy?.$modal.msgError('导出选中的数据失败');
  }
}

/** 详情按钮操作 */
const handleView = async (row?: Nyt7FarmerInsuranceInfoVO) => {
  reset();
  const _id = row?.id || ids.value[0];
  const res = await getNyt7FarmerInsuranceInfo(_id);
  Object.assign(form2.value, res.data);
  console.log(form2.value);
  dialogView.visible = true;
  dialogView.title = '农户投保信息详情';
}


/* 打开数据导入的对话框 */
const excelOpen = ref(false);

function handleImport() {
  excelOpen.value = true;
}

// 存储选择的文件
const selectedFile = ref(null);

// 文件选择变化时的处理
const handleChange = (file) => {
  selectedFile.value = file.raw;
};

// 提交上传
const submitUpload = async () => {
  if (!selectedFile.value) {
    proxy?.$modal.msgError('请先选择文件');
    return;
  }

  try {
    proxy?.$modal.loading('正在上传excel，请稍候...');
    const res = await importExcel(selectedFile.value);
    if (res.code === 200) {
      proxy?.$modal.msgSuccess('上传excel成功');
      excelOpen.value = false;
      getList();
    } else {
      proxy?.$modal.msgError(res.msg);
    }
  } catch (error) {
    proxy?.$modal.msgError('上传excel失败');
  } finally {
    proxy.$modal.closeLoading();
    uploadRef.value.clearFiles();
  }

};

/** 下载导入模版 */
const handleExportTemplate = () =>{
  proxy?.download(
    'Nyt7FarmerInsuranceInfo/Nyt7FarmerInsuranceInfo/template',
    {},
    `农户信息导入模版.xlsx`
  )
}


onMounted(() => {
  getList();
});
</script>
